<?php
    class FamiliesController extends AppController {
        /*
         * Attributes
         */
        var $name = 'Families';
        
        function create(){
            $this->loadModel('Person');
            if(!empty($this->data)){
                $this->data['Person'] = array('id' => $this->Auth->user('id'));
                //$this->data['
                //print_r($this->data);
				if($this->Family->save($this->data)){
				    $id = $this->Family->id;
					$this->Session->setFlash($this->data['Family']['name'] . ' was succesfully created! ');
					$this->Family->query("UPDATE families_people SET admin=1 WHERE family_id=$id");
					$this->redirect('/events/index');
				}else{
					//$this->Session->setFlash('Family was not created, please try again. ');
				}
			}
		}


		/*
		 * Manage family membership (add, remove users and change admin status)
		 */
		function manage() {

			$this->loadModel('Person');

			// Get the parameters we will need
            $passed = $this->params['named'];
            $params = $this->extractnamedParams(array('family'),
                                                array('sort' => false, 'page' => false));
            if (!$params) {
                // Required parameters were not present (Namely family id)
                $this->Session->setFlash("Cannot manage a family without providing a family id");
                $this->redirect('/events');
            }
            
            // verify that the user has access to change sharing for the passed in family id
			$current_user = $this->Auth->user('id');
			if (!$this->Family->isPersonFamilyAdmin($current_user, $params['family'])) {
				// Bad user!!
                $this->Session->setFlash("You do not have permissions to manage this family");
                $this->redirect('/events');
			}


			$this->set('current_family_id', $params['family']);
			$this->set('current_family_name', $this->Family->getFamilyName($params['family']));

			// get users in this family
			$user_ids = $this->Family->getPeopleFromFamily($params['family']);

			$users = $this->Person->getPeopleFromIDs($user_ids);
			$this->set('users', $users);

			$current_admin = $this->Person->getPersonFromID($this->Auth->user('id'));
			$this->set('current_admin', $current_admin);

			$family_user_admin_status = $this->Family->getFamilyPersonAdminStatus($params['family']);
			$this->set('family_user_admin_status', $family_user_admin_status);			
		}

		/*
		 * This controller performs the update for family membership changes
		 */
		function updatefamily() {
			$this->autoRender = false;

			// Get the parameters we will need
            $passed = $this->params['named'];
            $params = $this->extractnamedParams(array('family'),
                                                array('sort' => false, 'page' => false));

	
            if (!$params) {
                // Required parameters were not present (Namely event number)
                $this->Session->setFlash("Cannot save family membership without providing a family id");
                $this->redirect('/events');
            }

			// verify that the user has access to change sharing for the passed in family id
			$current_user = $this->Auth->user('id');
			if (!$this->Family->isPersonFamilyAdmin($current_user, $params['family'])) {
				// Bad user!!
                $this->Session->setFlash("You do not have permissions to manage this family");
                $this->redirect('/events');
			}

			$user_ids = $this->Family->getPeopleFromFamily($params['family']);
			$users = $this->Person->getPeopleFromIDs($user_ids);
			$usernames = $this->Person->getPeopleUsernames($user_ids);

			$current_admin = $this->Person->getPersonFromID($current_user);

			$family_user_admin_status = $this->Family->getFamilyPersonAdminStatus($params['family']);
	
			// only users that are already registered will be added to this family
			// keep track of the usernames that are not registered
			$not_registered = array();
			
			$submit_data = array();
			foreach ($this->params['form'] as $modified_user => $admin_status) {
				$submit_data[$this->_fixHostname($modified_user)] = $admin_status;
			}
				
			
			if(!empty($this->params['form'])){

				// check for new users added to this family
				foreach ($submit_data as $username => $admin_status) {
					
					$cur_uid = trim($this->Person->getPersonIdFromUsername(trim($username)));
				
					// is current user not in this family already?  if so, add user to this family
					if (!in_array($username, $usernames)) {
						if ($username == $usernames[$current_admin['id']]) {
							// we should never get here (the admin editing the event should not be in the list
							// of users to be added to the family; fontend takes care of that
							debug("FATAL ERROR: current logged in username should not be in the list of users" +
								  " to be added to this family");
							debug($username, true);
							exit();
						}
											
						// $username is not currently registered
						if ($cur_uid == '') {
							array_push($not_registered, $username);
							continue;
						}
						
						// prepare cakephp model for saving						
						$this->Family->FamiliesPerson->create($data);
						$data['FamiliesPerson'] = array();
						$data['FamiliesPerson']['family_id'] = $params['family'];
						$data['FamiliesPerson']['person_id'] = $cur_uid;
						$data['FamiliesPerson']['admin'] = $admin_status;
										
						$this->Family->FamiliesPerson->save($data);                        

						unset($data);
					}
					else {
						// has the user admin status change?
						if ($family_user_admin_status[$cur_uid] != $admin_status) {
							$record_to_update = $this->Family->FamiliesPerson->find('first', 
													array('conditions' =>
															array('person_id' => $cur_uid,
																  'family_id' => $params['family'])));
						
							$this->Family->FamiliesPerson->read('FamiliesPerson.admin', $record_to_update['FamiliesPerson']['id']);
							$this->Family->FamiliesPerson->set('admin', $admin_status);
							$this->Family->FamiliesPerson->save();
						}
					}
				}
			}

			// check for users that have been removed from this family
			foreach ($users as $user) {
				// if a user that used to be in this family is not longer present 
				// in the update request, remove the user from this family
				// of course, ignore the admin that's doing the current request; 
				if (!array_key_exists($user['username'], $submit_data) && ($user['id'] != $current_admin['id'])) {
					// find the id in the FamiliesPerson table that corresponds to the current
					// family and person
					$record_to_remove = $this->Family->FamiliesPerson->find('first', array('conditions' =>
																array('person_id' => $user['id'],
																	  'family_id' => $params['family'])));
																	  
					$this->Family->FamiliesPerson->delete($record_to_remove['FamiliesPerson']['id'], false);
				}
			}

			// are any of the email addresses that were requested to be added to this family not registered?
			if (count($not_registered) > 0) {
				$emails_not_registered = implode(', ', $not_registered);
				$this->Session->setFlash("Family membership was succesfully saved.  ".
							"However, the following users are not registered and were not added to this family: ".
							$emails_not_registered . ". They can sign up and then you can add them to the family");
			}
			else {
				$this->Session->setFlash("Family membership was succesfully saved");
			}
			
			$this->redirect('/events');
			

		}
		
		// cake php replaces the . in the domain name when submitting and email in a form with an underscores
		// let's fix that
		function _fixHostname($email) {
			preg_match('/^(.*)@(.*)/', $email, $matches);
			
			$user = $matches[1];
			$hostname = $matches[2];
			
			return $user.'@'.str_replace('_', '.', $hostname);
		}
    }
?>
